package com.example.landlord.demo.Service.Impl;

import com.example.landlord.demo.Controller.request.ForgetRequest;
import com.example.landlord.demo.Controller.request.RegisterRequest;
import com.example.landlord.demo.Entity.User;
import com.example.landlord.demo.Mapper.UserMapper;
import com.example.landlord.demo.Exception.ServiceException;
import com.example.landlord.demo.Service.ISendEmailService;
import com.example.landlord.demo.total.TotalV;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SendEmailService implements ISendEmailService {
    private Map<String, Long> timeMap = new HashMap<>(); // 记录存储数据的时间
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${mail.username}")
    private String from;
    @Autowired
    UserMapper userMapper;

    public void sendcodeEmail(RegisterRequest request) {
        String uname = request.getUName();
        String to = request.getEmail();
        if(uname == null || uname.trim().isEmpty()){
            throw new ServiceException("请输入用户名");
        }
        if(request.getUPwd() == null || request.getUPwd().trim().isEmpty()) {
            throw new ServiceException("请输入密码");
        }
        SimpleMailMessage message = new SimpleMailMessage();
        String subject = "【IT斗地主】";
        // 生成6位随机数
        Random random = new Random();
        int codeInt = random.nextInt(900000) + 100000;
        String code = String.valueOf(codeInt);

        // 删除一分钟前加入的数据
        long currentTime = System.currentTimeMillis();
        List<String> usernamesToRemove = new ArrayList<>();
        for (Map.Entry<String, Long> entry : timeMap.entrySet()) {
            String username = entry.getKey();
            long time = entry.getValue();
            if (currentTime - time >= 60 * 1000) {
                usernamesToRemove.add(username);
            }
        }
        for (String username : usernamesToRemove) {
            TotalV.verificationCodes.remove(username);
            timeMap.remove(username);
        }

        // 将用户名与随机数对应存放在Map中
        TotalV.verificationCodes.put(uname, code);
        timeMap.put(uname, currentTime);

        String text = "<html><body>" +
                "<h1 style=\"color: #007bff;\">尊敬的" + uname + "用户，你好：</h1>" +
                "<p style=\"font-size: 18px;\">欢迎使用<span style=\"color: #ff0000; font-weight: bold;\">IT斗地主</span>。</p>" +
                "<p>您的验证码是：<span style=\"font-size: 24px; font-weight: bold;\">" + code + "</span></p>" +
                "<p>感谢您的使用！</p>" +
                "</body></html>";
        System.out.println(code);
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        javaMailSender.send(message);
        printCodeMapData();
        System.out.println(TotalV.verificationCodes.get(uname));

    }

//找回密码
public void sendPassword(ForgetRequest request) {
    String uname = request.getUName();
    String to = request.getEmail();
    User user = userMapper.getPassword(request);

    if (user == null) {
        throw new ServiceException("该用户未注册");
    }
    String uPwd = user.getUPwd();


    if(uname == null ||uname.trim().isEmpty()){
        throw new ServiceException("请输入用户名");
    }
    SimpleMailMessage message = new SimpleMailMessage();
    String subject = "【IT斗地主】找回密码通知";
    String text = "<html>"
            + "<head>"
            + "<style>"
            + "body { font-family: Arial, sans-serif; color: #333333; }"
            + "h1 { color: #0088cc; }"
            + "p { margin-bottom: 10px; }"
            + "</style>"
            + "</head>"
            + "<body>"
            + "<h1>尊敬的用户，您好！</h1>"
            + "<p>您正在进行密码找回操作，您的密码为：<strong>" + uPwd + "</strong></p>"
            + "<p>请妥善保管您的账号和密码，并及时修改密码以确保账号安全。</p>"
            + "<p>如有任何疑问或需要协助，请随时联系我们的客服团队。</p>"
            + "<p>祝您游戏愉快！</p>"
            + "<p><em>ITNMB运营团队</em></p>"
            + "</body>"
            + "</html>";
    message.setFrom(from);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(text);
    javaMailSender.send(message);
}

    @Scheduled(fixedRate = 1000) // 每秒钟执行一次
    public void deleteExpiredData() {
        long currentTime = System.currentTimeMillis();

        List<String> usernamesToRemove = new ArrayList<>();

        for (Map.Entry<String, Long> entry : timeMap.entrySet()) {
            String username = entry.getKey();
            long time = entry.getValue();

            if (currentTime - time >= 60 * 1000) {
                usernamesToRemove.add(username);
            }
        }

        for (String username : usernamesToRemove) {
            TotalV.verificationCodes.remove(username);
            timeMap.remove(username);
        }

        printCodeMapData();
    }

    // 打印测试Map函数
    public void printCodeMapData() {
        for (Map.Entry<String, String> entry : TotalV.verificationCodes.entrySet()) {
            String username = entry.getKey();
            String code = entry.getValue();
            System.out.println("Username: " + username + ", Code: " + code);
        }
        System.out.println("---------------");
    }
}
